package cn.com.cifi.mars.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.com.cifi.mars.bean.dto.OrgDTO;
import cn.com.cifi.mars.bean.dto.SysProjectFetchNumberDto;
import cn.com.cifi.mars.bean.vo.sys.req.UpdateSysProjectFetchNumberParam;
import cn.com.cifi.mars.bean.vo.sys.rsp.SysProjectFetchNumberVo;
import cn.com.cifi.mars.common.exception.MsgException;
import cn.com.cifi.mars.constant.CodeEnum;
import cn.com.cifi.mars.constant.Constants;
import cn.com.cifi.mars.constant.FetchNnumberEnum;
import cn.com.cifi.mars.constant.IsDeleteEnum;
import cn.com.cifi.mars.entity.common.SysDictionary;
import cn.com.cifi.mars.entity.common.SysProjectFetchNumber;
import cn.com.cifi.mars.entity.common.SysProjectFetchNumberLog;
import cn.com.cifi.mars.mapper.mars.SysDictionaryMapper;
import cn.com.cifi.mars.mapper.mars.SysProjectFetchNumberLogMapper;
import cn.com.cifi.mars.mapper.mars.SysProjectFetchNumberMapper;
import cn.com.cifi.mars.service.MymService;
import cn.com.cifi.mars.service.SysProjectFetchNumberService;
import cn.com.cifi.mars.service.VsNosTradedataviewformarsService;
import cn.com.cifi.mars.util.UUIDUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yyd
 * @since 2019-09-21
 */
@Slf4j
@Service
public class SysProjectFetchNumberServiceImpl extends ServiceImpl<SysProjectFetchNumberMapper, SysProjectFetchNumber> implements SysProjectFetchNumberService {
	@Autowired
	private SysProjectFetchNumberMapper sysProjectFetchNumberMapper;
	@Autowired
	private SysDictionaryMapper sysDictionaryMapper;
	@Autowired
	private SysProjectFetchNumberLogMapper sysProjectFetchNumberLogMapper;
	@Autowired
	private VsNosTradedataviewformarsService vsNosTradedataviewformarsService;
	@Autowired
	private MymService mymService; 
	
	/**
	 * 拉取项目分期区域到取数系统表
	 */
	@Override
	public int init(String projectId) {
		log.info("=================初始化项目取数表  start==========================================="+LocalDateTime.now());
		List<OrgDTO> orgList = sysProjectFetchNumberMapper.selectProjectOrgList(projectId,null);
		initProjectFetchNumber(orgList);
		log.info("=================初始化项目取数表  end==========================================="+LocalDateTime.now());
		return 1;
	}

	/**
	 * 更改取数系统
	 */
	@Transactional
	@Override
	public int update(UpdateSysProjectFetchNumberParam param) {
		SysProjectFetchNumber bean = sysProjectFetchNumberMapper.selectById(param.getId());
		if(null==bean) {
			throw new MsgException(CodeEnum.SYS_PROJECT_FETCH_ERROR);
		}
		if(!StringUtils.isNotBlank(bean.getRegionId())) {
			throw new MsgException(CodeEnum.SYS_REGION_ID_ERROR);
		}
		if(!StringUtils.isNotBlank(bean.getProjectId())) {
			throw new MsgException(CodeEnum.SYS_PROJECT_ERROR);
		}
		
		LocalDateTime ldt=LocalDateTime.now();
		if(ldt.isEqual(bean.getEffectiveDate())) {
			throw new MsgException(CodeEnum.SYS_EFFECTIVEDATE_ERROR);
		}
		//根据字典code获取字典名称
		QueryWrapper<SysDictionary> qw=new QueryWrapper<>();
		qw.eq("type_code", Constants.COUNTING_SYSTEM);
		qw.eq("dict_value", param.getCountingSystemId());
		SysDictionary sysDictionary=sysDictionaryMapper.selectOne(qw);
		if(null==sysDictionary) {
			throw new MsgException(CodeEnum.DICT_TYPE_ERROR);
		}
		
		//添加取数系统历史表
		SysProjectFetchNumberLog fnl=new SysProjectFetchNumberLog();
		fnl.setCityId(bean.getCityId());
		fnl.setCityName(bean.getCityName());
		fnl.setCountingSystemId(bean.getCountingSystemId());
		fnl.setCountingSystemName(bean.getCountingSystemName());
		fnl.setCreateTime(LocalDateTime.now());
		fnl.setEffectiveDate(bean.getEffectiveDate());
		fnl.setProjectId(bean.getProjectId());
		fnl.setProjectName(bean.getProjectName());
		fnl.setRegionId(bean.getRegionId());
		fnl.setRegionName(bean.getRegionName());
		fnl.setStagesId(bean.getStagesId());
		fnl.setStagesName(bean.getStagesName());
		fnl.setId(UUIDUtils.create());
		int add=sysProjectFetchNumberLogMapper.insert(fnl);
		
		//编辑新的记录
		SysProjectFetchNumber his=bean;
		his.setCityId(bean.getCityId());
		his.setCityName(bean.getCityName());
		his.setCountingSystemId(param.getCountingSystemId());
		his.setCountingSystemName(sysDictionary.getDictName());
		his.setCreateTime(LocalDateTime.now());
		his.setEffectiveDate(ldt);
		his.setProjectId(bean.getProjectId());
		his.setProjectName(bean.getProjectName());
		his.setRegionId(bean.getRegionId());
		his.setRegionName(bean.getRegionName());
		his.setStagesId(bean.getStagesId());
		his.setStagesName(bean.getStagesName());
		int upd=sysProjectFetchNumberMapper.updateById(his);
		return upd;
	}

	/**
	 * 分页查询项目取数
	 */
	@Override
	public SysProjectFetchNumberVo querySysProjectFetchNumber(String current,String pageSize,String regionId, String projectId,
			String countingSystemId,String beginTime,String endTime,String cityId,String stagesId) {
		SysProjectFetchNumberVo vo=new SysProjectFetchNumberVo();
		Page<SysProjectFetchNumberDto>pageDto=new Page<>();
		//参数当前页
		pageDto.setCurrent(Integer.parseInt(current));
		//参数每页数量
		pageDto.setSize(Integer.parseInt(pageSize));
		List<SysProjectFetchNumberDto> list = sysProjectFetchNumberMapper.selectSysProjectFetchNumberPage(pageDto, countingSystemId, regionId, projectId,beginTime,endTime,cityId,stagesId);
		vo.setCurrent(pageDto.getCurrent());
		vo.setPages(pageDto.getPages());
		vo.setPageSize(pageDto.getSize());
		vo.setTotal(pageDto.getTotal());
		vo.setList(list);
		return vo;
	}
	
	
	/**
	 * 字符串日期转换LocalDateTime
	 * @return
	 */
	public static LocalDateTime getStringParseTime(String time) {
		DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return LocalDateTime.parse(time,df);
	}

	/**
	 * 增量同步主数据到项目取数表
	 */
	@Override
	public int syncProjectFetchNumber(String projectId,String stageId) {
		List<OrgDTO> orgList = sysProjectFetchNumberMapper.selectProjectOrgList(projectId,stageId);
		initProjectFetchNumber(orgList);
		return 1;
	}

	/**
	 * 根据分期id和日期查询项目取数信息
	 * @param projectFid
	 * @param now
	 * @return
	 */
	@Override
	public SysProjectFetchNumber selectByFid(String projectFid) {
		return sysProjectFetchNumberMapper.selectFetchNumberByFid(projectFid);
	}

	@Override
	public List<SysProjectFetchNumber> selectByProjectId(String projectId) {
		return sysProjectFetchNumberMapper.selectByProjectId(projectId);
	}

	/**
	 * 优化主数据到项目取数表 2）新项目初始化
	 * 	操盘方式
			  DULICP  =独立操盘-------营销操盘------明源系统
			  LIANHECP=联合操盘-------非营销操盘-----Nos系统
			  BUCP    =不操盘    -------非营销操盘-----Nos系统
			取数系统配置及初始化：
		    1）上线系统初始化：在明源项目分期设置为明源，在NOS系统设置为NOS；两个系统都不存在，则默认设置为明源。
		    2）新项目初始化：营销操盘默认设置为明源，营销不操盘默认设置为NOS，新建货值版本时检查是否设置，如果没设置提醒先设置；
		    3）修改取数系统：业务人员先把NOS数据全部从NOS迁移到明源后，告知系统管理员修改设置，从修改设置当时生效；修改后保留历史记录，但已无效；
	 */
	@Transactional
	public void initProjectFetchNumber(List<OrgDTO> list) {
		List<SysProjectFetchNumber> fetchNumberList = sysProjectFetchNumberMapper.selectAll();
		for(OrgDTO dto : list) {
			String stagesId = dto.getStageId();
			String stagesName = dto.getStageName();
			String projectId = dto.getProjectId();
			String projectName = dto.getProjectName();
			String cityId = dto.getCityId();
			String cityName = dto.getCityName();
			String regionId = dto.getRegionId();
			String regionName = dto.getRegionName();
			String effectiveDate = dto.getCreateDate();
			/*
			 * 出现分期id与项目id一致的错误数据，暂无排查到原因
			 * 强制剔除错误数据，并记录日志
			 */
			if(stagesId.equals(projectId)){
				continue;
			}
			
			//判断分期是否存在取数系统
			SysProjectFetchNumber sysProjectFetchNumber = getFetchNumberByStageId(stagesId,fetchNumberList);
			if(sysProjectFetchNumber != null) {
				sysProjectFetchNumber.setProjectId(projectId);
				sysProjectFetchNumber.setProjectName(projectName);
				sysProjectFetchNumber.setStagesId(stagesId);
				sysProjectFetchNumber.setStagesName(stagesName);
				sysProjectFetchNumber.setCityId(cityId);
				sysProjectFetchNumber.setCityName(cityName);
				sysProjectFetchNumber.setRegionId(regionId);
				sysProjectFetchNumber.setRegionName(regionName);
				sysProjectFetchNumberMapper.updateById(sysProjectFetchNumber);
				continue;
			}
			
			String countingSystemId="";
			String countingSystemName="";
			
			SysProjectFetchNumber bean = new SysProjectFetchNumber();
			bean.setCreateTime(LocalDateTime.now());
			bean.setProjectId(projectId);
			bean.setProjectName(projectName);
			bean.setStagesId(stagesId);
			bean.setStagesName(stagesName);
			bean.setRegionId(regionId);
			bean.setRegionName(regionName);
			bean.setCountingSystemId(countingSystemId);
			bean.setCountingSystemName(countingSystemName);
			bean.setCityId(cityId);
			bean.setCityName(cityName);
			if(StringUtils.isNotBlank(effectiveDate)) {
				bean.setEffectiveDate(getStringParseTime(effectiveDate));
			}
			bean.setId(UUIDUtils.create());
			bean.setCreateTime(LocalDateTime.now());
			sysProjectFetchNumberMapper.insert(bean);
			
			//添加取数系统历史表
			SysProjectFetchNumberLog fnl = new SysProjectFetchNumberLog();
			fnl.setId(UUIDUtils.create());
			fnl.setCityId(bean.getCityId());
			fnl.setCityName(bean.getCityName());
			fnl.setCountingSystemId(bean.getCountingSystemId());
			fnl.setCountingSystemName(bean.getCountingSystemName());
			fnl.setCreateTime(LocalDateTime.now());
			fnl.setEffectiveDate(bean.getEffectiveDate());
			fnl.setProjectId(bean.getProjectId());
			fnl.setProjectName(bean.getProjectName());
			fnl.setRegionId(bean.getRegionId());
			fnl.setRegionName(bean.getRegionName());
			fnl.setStagesId(bean.getStagesId());
			fnl.setStagesName(bean.getStagesName());
			sysProjectFetchNumberLogMapper.insert(fnl);
		}
	}
	
	private SysProjectFetchNumber getFetchNumberByStageId(String stagesId,List<SysProjectFetchNumber> fetchNumberList) {
		if(CollectionUtils.isNotEmpty(fetchNumberList)) {
			for(SysProjectFetchNumber obj : fetchNumberList) {
				if(stagesId.equals(obj.getStagesId())) {
					return obj;
				}
			}
		}
		return null;
	}

	@Transactional
	@Override
	public int delete(String id) {
		return sysProjectFetchNumberMapper.deleteById(id);
	}
	
	/**
	 * 获取明源视图项目
	 * @return
	 */
	public List<String> getMyCodeList() {
		return mymService.selectMyCodeList(IsDeleteEnum.NO.getKey()+"");
	}
	
	/**
	 * 获取nos视图项目
	 * @return
	 */
	public List<String> getNosCodeList() {
		return vsNosTradedataviewformarsService.selectNosCodeList(IsDeleteEnum.NO.getKey()+"");
	}
	
	/**
	 * 获取初始化取数系统
	 * 取数系统配置及初始化：
                 上线系统初始化：在明源项目分期设置为明源，在NOS系统设置为NOS；两个系统都不存在，则默认设置为明源。
	 * @param myList
	 * @param nosList
	 * @param code
	 * @return
	 */
	public String getFetchNum(List<String>myList,List<String>nosList,String code) {
		String msg="";
		if(myList != null && myList.size() > 0) {
			if(myList.contains(code)) {
				msg = FetchNnumberEnum.MY.getKey();
			}
		}
		if(nosList != null && nosList.size()>0) {
			if(nosList.contains(code)) {
				msg = FetchNnumberEnum.NOS.getKey();
			}
		}
		if(!StringUtils.isNotBlank(msg)) {
			msg = FetchNnumberEnum.MY.getKey();
		}
		return msg;
	}
	
}
